<template>
    <div style="width: 100%;height: 100%;background-color: #fff;border: 0.0625rem solid #ccc;">
        <div class="df aic jcc">
            <canvas ref="canvas" class="jSignature" tabindex="0" @mousedown="onMouseDown" />
        </div>
        <footer slot="footer" class="dialog-footer df jcc mb10">
            <el-button size="small" @click.native.prevent="clearPanel">取消</el-button>
            <el-button size="small" type="primary" @click="confirm">确认签名</el-button>
        </footer>
    </div>
</template>
  
<script>
import { defineComponent, ref, nextTick } from 'vue'
export default defineComponent({
    name: 'environAmbitus',
    setup() {
        const canvas = ref(null)

        // 开始签名
        function onMouseDown(e) {
            const el = e.target || e.srcElement
            const ctx = el.getContext('2d')
            ctx.beginPath()
            ctx.moveTo(e.offsetX, e.offsetY)
            ctx.lineTo(e.offsetX, e.offsetY)
            ctx.stroke()
            el.onmousemove = function (e) {
                if (e.which === 0) {
                    el.onmousemove = null
                    el.onmouseup = null
                    return
                }
                ctx.lineTo(e.offsetX, e.offsetY)
                ctx.stroke()
            }
            el.onmouseup = function () {
                el.onmousemove = null
                el.onmouseup = null
            }
            el.focus()
        }

        // 清空签名
        function clearPanel(e) {
            nextTick(() => {
                // const el = canvas;
                const ctx = canvas.value.getContext("2d");
                ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
            });
        }

        // 确认签名
        function confirm() {
            nextTick(() => {
                try {
                    // const canvas = this.$refs["canvas"];
                    const blank = document.createElement("canvas"); // 创建一个空canvas对象
                    blank.width = canvas.value.width;
                    blank.height = canvas.value.height;
                    console.log(canvas.value.toDataURL());
                } catch (e) {
                    console.warn(e);
                }
            });
        }
        return { onMouseDown, confirm, clearPanel, canvas }
    }
})
</script>